<?php

namespace App\Exceptions;

use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Database\QueryException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\ValidationException;
use Stancl\Tenancy\Exceptions\TenantCouldNotBeIdentifiedOnDomainException;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Throwable;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array<int, class-string<Throwable>>
     */
    protected $dontReport = [
        //
    ];

    protected $levels = [
        100 => 'debug',
        200 => 'info',
        300 => 'notice',
        400 => 'notice',
        403 => 'notice',
        500 => 'warning',
        600 => 'error',
        700 => 'critical',
        800 => 'alert',
        900 => 'emergency',
    ];
    protected $msg = [
        100 => '通信成功',
        200 => '请求处理成功',
        300 => '身份验证失败',
        400 => '参数验证失败',
        403 => '无法请求改资源数据',
        500 => '请求地址或类型错误',
        600 => '数据库语句错误',
        700 => '服务端出现异常',
        800 => '服务超时请重试',
        900 => '程序错误请重试',
    ];

    protected $code = 200;

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array<int, string>
     */
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     *
     * @return void
     */
    public function register()
    {
        $this->reportable(function (Throwable $e) {
            //
        });
    }

    public function render($request, $exception)
    {

        $this->code = $exception->getCode() ?? 201;
        $msg = $exception->getMessage();
        $httpStatus = 500;
        if ($exception instanceof AccessDeniedHttpException) {
            $this->code = 403;
            $httpStatus = 403;
        } elseif ($exception instanceof NotFoundHttpException) {
            $this->code = 500;
            $httpStatus = 404;
        } elseif ($exception instanceof MethodNotAllowedHttpException) {
            $this->code = 500;
            $httpStatus = 405;
        } elseif ($exception instanceof ValidationException) {
            $this->code = 422;
            $httpStatus = 200;
            $msg = $exception->validator->messages()->first();
        } elseif ($exception instanceof BusinessException) {
            $this->code = $exception->getCode() == 0 ? 10001 : $exception->getCode();
            $httpStatus = 200;
        } elseif ($exception instanceof HttpException) {
            $this->code = 500;
        } elseif ($exception instanceof ModelNotFoundException) {
            $this->code = 600;
        } elseif ($exception instanceof QueryException) {
            $this->code = 600;
        } elseif ($exception instanceof \ReflectionException) {
            $this->code = 700;
        } elseif ($exception instanceof \RuntimeException) {
            $this->code = 800;
        } elseif ($exception instanceof \ErrorException) {
            $this->code = 900;
        } elseif ($exception instanceof \Exception) {
            $this->code = 900;
        }
        $result = [
            'code' => $this->code,
            'msg' => $this->msg[$this->code] ?? $msg,
            'data' => []
        ];
        $error_context = $this->convertExceptionToArray($exception);
        if (config('app.debug')) {
            $result['error_msg'] = $msg;
            $result['error_line'] = $exception->getFile() . ':' . $exception->getLine();
            $result['error_context'] = $error_context;
        }
        //出现非200的错误，记录日志
        if (isset($this->levels[$this->code]) && $httpStatus !== 200) {
            Log::log($this->levels[$this->code], $result['msg'], $error_context);
        }
        return response()->json($result, $httpStatus)->setEncodingOptions(JSON_UNESCAPED_UNICODE);
    }
}
